package com.epam.cdp.ejb.statefull;

import java.util.ArrayList;
import java.util.List;

import javax.annotation.PostConstruct;
import javax.annotation.PreDestroy;
import javax.ejb.PostActivate;
import javax.ejb.PrePassivate;
import javax.ejb.Remove;
import javax.ejb.Stateful;

import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;

import com.epam.cdp.ejb.utilities.GadgetWindow;
import com.epam.cdp.ejb.utilities.Position;

@Stateful
public class UserSessionBean implements UserSession {

	private static final Log log = LogFactory.getLog(UserSessionBean.class);
	
	private List<GadgetWindow> windows;
	
	public UserSessionBean() {
		this.windows = new ArrayList<GadgetWindow>();
	}
	
	@Override
	public GadgetWindow getByName(String name) {
		GadgetWindow foundWindow = null;
		if (name != null) {
			for (GadgetWindow item : windows) {
				if (name.equals(item.getName())) {
					foundWindow = item;
				}
			}
		}
		return foundWindow;
	}

	@Override
	public GadgetWindow openNewWindow(String name, Position possition) {
		GadgetWindow window = new GadgetWindow(name, possition);
		windows.add(window);
		return window;
	}

	@Override
	public void closeWindow(String name) {
		GadgetWindow window = getByName(name);
		if (window != null) {
			windows.remove(window);
		}
	}

	@Override
	public List<GadgetWindow> getAllWindows() {
		return windows;
	}

	@PostConstruct
	public void postConstruction() {
		log.info(this.getClass().getSimpleName() + " enterprise bean was created. (@PostConstruct)");
	}
	
	@PrePassivate
	public void prePassivate() {
		log.info(this.getClass().getSimpleName() + " enterprise bean will be passivated. (@PrePassivate)");
	}
	
	@PostActivate
	public void postActivate() {
		log.info(this.getClass().getSimpleName() + " enterprise bean was activated. (@PostActivate)");
	}
	
	@PreDestroy
	public void preDestroy() {
		log.info(this.getClass().getSimpleName() + " enterprise bean will be destroyed. (@PreDestroy)");
	}
	
	@Remove
	public void remove() {
		log.info(this.getClass().getSimpleName() + " enterprise bean will be removed. (@Remove)");
	}
	
}
